package com.itheima.appserver.service;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.appserver.config.HuanxinConfig;
import com.itheima.appserver.excepiton.BusinessException;
import com.itheima.appserver.excepiton.ErrorResult;
import com.itheima.commons.constants.Constants;
import com.itheima.commons.pojo.domain.HuanxinUser;
import com.itheima.commons.pojo.domain.User;
import com.itheima.dubbo.interfaces.HuanxinUserApi;
import com.itheima.dubbo.interfaces.UserApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author yaohu
 * @date 2021/12/3
 * @Version 1.0
 * @describe
 */
@Service
public class UserService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private RequestService requestService;

    @Autowired
    private HuanxinConfig huanXinConfig;

    @Reference
    private UserApi userAPI;

    @Reference
    private HuanxinUserApi huanxinUserApi;

    public void sendLoginMsg(String phone) {
        // 判断这个手机号码是否是合法的
        if (!Validator.isMobile(phone)) {
            // 如果不合法直接抛出异常
            throw new BusinessException(ErrorResult.phoneNumError());
        }

        // 判断之前是否以经发送过验证码，还没有失效 5
        String code = redisTemplate.opsForValue().get(Constants.SMS_CODE + phone);
        if (!StrUtil.isBlank(code)) {
            throw new BusinessException(ErrorResult.sendCodeError());
        }

        /*// 生成一个随机的验证码
        String randomCode = RandomUtil.randomNumbers(6);
        System.out.println("randomCode = " + randomCode);

        // 调用阿里云平台发送验证码
        Boolean result = SendMsgUtil.sendMsg(phone, Constants.SMS_CODE_TEMPLATE, randomCode);
        if (!result) {
            // 发送过验证码
            throw new BusinessException(ErrorResult.sendMSGError());
        }*/

        // 测试验证码
        String randomCode = "123456";

        // 把验证码存储到redis中 有效期5分钟
        redisTemplate.opsForValue().set(Constants.SMS_CODE + phone, randomCode, 5, TimeUnit.MINUTES);
    }

    public Map<String, Object> loginVerification(String phone, String verificationCode) {
        // 判断这个手机号码是否是合法的
        if (!Validator.isMobile(phone)) {
            // 如果不合法直接抛出异常
            throw new BusinessException(ErrorResult.phoneNumError());
        }

        // 判断验证码是否一致
        String code = redisTemplate.opsForValue().get(Constants.SMS_CODE + phone);
        if (null == code || null == verificationCode || !code.equals(verificationCode)) {
            throw new BusinessException(ErrorResult.verificationCodeError());
        }

        // 删除验证码
        redisTemplate.delete(Constants.SMS_CODE + phone);

        // 判断是否为新用户
        User user = userAPI.findUserByPhoneNum(phone);
        HashMap<String, Object> hashMap = new HashMap<>();
        // 默认是老用户
        hashMap.put("isNew", false);
        if (ObjectUtil.isNull(user)) {
            // 1.新用户赋值
            user = userAPI.addUser(User.builder()
                    .mobile(phone)
                    .password(SecureUtil.md5(Constants.INIT_PASSWORD))
                    .created(new Date())
                    .updated(new Date())
                    .build());
            hashMap.put("isNew", true);

            // 2.给环信发送一个请求，让环信注册一个新用户
            HttpResponse response = requestService.execute(
                    huanXinConfig.getUrl() + huanXinConfig.getOrgName() + "/" + huanXinConfig.getAppName() + "/users",
                    JSONUtil.createObj().set("username", "HX_" + user.getId()).set("password", SecureUtil.md5(user.getMobile())).toString(),
                    Method.POST);
            if (!response.isOk()) {
                throw new BusinessException(ErrorResult.userRegisterError());
            }

            // 3.保存到tb_huanxin_user表中
            huanxinUserApi.addUser(HuanxinUser.builder()
                    .userId(user.getId())
                    .username("HX_" + user.getId())
                    .password(SecureUtil.md5(user.getMobile()))
                    .created(user.getCreated())
                    .updated(user.getUpdated())
                    .build());
        }

        // 生成Token
        HashMap<String, Object> map = new HashMap<>();
        map.put("uid", user.getId());
        map.put("phoneNum", user.getMobile());
        map.put(JWTPayload.EXPIRES_AT, DateTime.of(System.currentTimeMillis() + Constants.JWT_TIME_OUT));
        String token = JWTUtil.createToken(map, Constants.JWT_SECRET.getBytes());

        hashMap.put("token", token);
        return hashMap;
    }
}
